<?php

// $action est deja set par l'appellant

$limit = request::get('nbritems');
if (!$limit) {
	$limit = 3;
}


/**
 *	Action GET equivalent INDEX
 *
 */

if ($action == "get") {

	$timestamp = request::get('timestamp');
	if (!$timestamp) {
		$timestamp = 0;
	}	
	$q = "SELECT * FROM scores WHERE timestamp > $timestamp ORDER BY timestamp DESC LIMIT $limit";
	
	sql::query($q);
	$data = sql::allFetchArray();
	$ret = array();
	foreach ($data as $d) {
		$d['timeRender'] = $d['time'] / 1000;
		
		$ret[] = $d;
	}
	echo(json_encode($ret));
}


/**
 *	Action getBestScores
 *
 */
 
if ($action == "getBestScores") {

	$timestamp = request::get('timestamp');
	$time = request::get('time');

	if (!$timestamp) {
		$timestamp = 0;
	}
	
	if (!$time) {
		$q = "SELECT * FROM scores WHERE timestamp > $timestamp ORDER BY time ASC LIMIT $limit";
	} else {
		$q = "SELECT * FROM scores WHERE timestamp > $timestamp AND time < $time ORDER BY time ASC LIMIT $limit";
	}
	
	sql::query($q);
	$data = sql::allFetchArray();
	
	$ret = array();
	foreach ($data as $d) {
		$d['timeRender'] = $d['time'] / 1000;
		
		$ret[] = $d;
		
	}
	echo(json_encode($ret));
}


if ($action == "add") {

	$new = $_REQUEST;
	$data = array();
	$data['time'] = request::get('time');
	$data['pseudo'] = request::get('pseudo');
	$data['timestamp'] = time();	

	OrmNode::upsert("scores", array_keys($data), $data);	
	echo(json_encode($new));
}




